import { roleConfig } from "../config/role.js";
import { http } from "@/common/service/service.js";
import { ACCESS_TOKEN } from "@/common/util/constants.js";

/**
 * 认证服务类
 */
class AuthService {
  constructor() {
    this.baseUrl = "http://localhost:8080";
    this.tokenKey = ACCESS_TOKEN;
    this.userInfoKey = "erp_user_info";
    this.currentUser = null;
  }

  /**
   * 用户登录
   */
  async login(username, password) {
    try {
      const response = await http.post("/sys/employee/login", {
        username,
        password,
      });

      const responseData = response.data;
      if (responseData.success) {
        const { token, userInfo } = responseData.result;

        // 存储token和用户信息
        console.log("Storing token:", token);
        uni.setStorageSync(ACCESS_TOKEN, token);
        uni.setStorageSync(this.userInfoKey, userInfo);
        
        // 验证存储是否成功
        const storedToken = uni.getStorageSync(ACCESS_TOKEN);
        console.log("Stored token verification:", storedToken);

        this.currentUser = userInfo;

        return {
          success: true,
          data: userInfo,
        };
      } else {
        return {
          success: false,
          message: responseData.message || "登录失败",
        };
      }
    } catch (error) {
      console.error("登录失败:", error);
      return {
        success: false,
        message: "网络错误，请重试",
      };
    }
  }

  /**
   * 用户登出
   */
  logout() {
    uni.removeStorageSync(ACCESS_TOKEN);
    uni.removeStorageSync(this.userInfoKey);
    this.currentUser = null;

    // 跳转到登录页
    uni.reLaunch({
      url: "/pages/login/login",
    });
  }

  /**
   * 获取存储的token
   */
  getToken() {
    return uni.getStorageSync(ACCESS_TOKEN);
  }

  /**
   * 检查是否已登录
   */
  isLoggedIn() {
    const token = this.getToken();
    return !!token;
  }

  /**
   * 获取当前用户信息
   */
  getCurrentUser() {
    if (!this.currentUser) {
      this.currentUser = uni.getStorageSync(this.userInfoKey);
    }
    return this.currentUser;
  }

  /**
   * 获取用户角色
   */
  getUserRole() {
    const user = this.getCurrentUser();
    if (!user || !user.userIdentity) {
      return null;
    }

    // 根据userIdentity映射角色
    const roleMap = {
      1: "sales_employee", // 销售员工
      2: "sales_manager", // 销售管理
      3: "warehouse_employee", // 仓库员工
      4: "warehouse_manager", // 仓库管理
      5: "production_employee", // 生产员工
      6: "production_manager", // 生产管理
    };

    return roleMap[user.userIdentity] || null;
  }

  /**
   * 获取当前角色信息
   */
  getCurrentRole() {
    const userRole = this.getUserRole();
    if (!userRole) return null;

    return roleConfig.roles[userRole] || null;
  }

  /**
   * 检查用户权限
   */
  hasPermission(permission) {
    const role = this.getUserRole();
    if (!role) return false;

    const roleInfo = roleConfig.roles[role];
    if (!roleInfo) return false;

    return roleInfo.permissions.includes(permission);
  }

  /**
   * 检查用户是否可以访问模块
   */
  canAccessModule(moduleKey) {
    const role = this.getUserRole();
    if (!role) return false;

    const roleInfo = roleConfig.roles[role];
    if (!roleInfo) return false;

    return roleInfo.modules.includes(moduleKey);
  }

  /**
   * 获取用户可访问的模块列表
   */
  getAccessibleModules() {
    const role = this.getUserRole();
    if (!role) return [];

    const roleInfo = roleConfig.roles[role];
    if (!roleInfo) return [];

    return roleInfo.modules
      .map((moduleKey) => roleConfig.modules[moduleKey])
      .filter(Boolean);
  }

  /**
   * 获取认证请求头
   */
  getAuthHeaders() {
    const token = this.getToken();
    return {
      "X-Access-Token": token,
      "Content-Type": "application/json",
    };
  }

  /**
   * 设置用户信息
   */
  setUserInfo(userInfo) {
    this.currentUser = userInfo;
    uni.setStorageSync(this.userInfoKey, userInfo);
  }

  /**
   * 刷新用户信息
   */
  async refreshUserInfo() {
    try {
      const response = await http.get("/sys/employeeLogin/info");

      const responseData = response.data;
      if (responseData.success) {
        const userInfo = responseData.result;
        this.setUserInfo(userInfo);
        return true;
      }
      return false;
    } catch (error) {
      console.error("刷新用户信息失败:", error);
      return false;
    }
  }
}

// 创建单例实例
const authService = new AuthService();

export default authService;
